<?php
ini_set('memory_limit', '1600M');

########File Paths#################
$samtools = '/usr/bin/samtools';
$dataDir = '/srv/http/anup/test/data/bam/';
$sqlDatabase = '/srv/http/anup/test/data/database.db';

#########GFF structure###############
$genefeatureName = 'gene';
$exonfeatureName = 'exon';
$exonGeneIdInAttribute = 'Parent';
###################################

function parse_attributes($attributes) {
        $extra = preg_split('/;/',$attributes);
        $meta = array();
        foreach($extra as $attribute) {
            preg_match('/(.*)="?(.*)"?|(.*)="?(.*)"?/',$attribute,$m);
            $meta[$m[1]] = $m[2];
        }
    return $meta; 
}

$db = new SQLite3($sqlDatabase);

if($_GET['action'] == 'gene_model_track') {

    $start = $_GET['start'];
    $stop = $_GET['stop'];
    $pixel = $_GET['pixel_size'];
    $chr_name = $_GET['chr_name'];
    $sql = "select * from gff g
    where seqid = '$chr_name' and 
    g.start <= $stop and $start <= g.end
    and g.feature = '$exonfeatureName'";
    #echo $sql;
    $results = $db->query($sql);

    
    while ($line = $results->fetchArray(SQLITE3_ASSOC)) {
    #foreach($out as $line) {
        $meta = parse_attributes($line['attributes']);
        
        $o[$meta[$exonGeneIdInAttribute]][] = array(
           'gene_id' =>$meta[$exonGeneIdInAttribute],
           'start' => $line['start'],
           'stop' => $line['end'],
           'strand' => $line['strand'],
           'genename' => $meta[$exonGeneIdInAttribute],
           'db_gene_id' => $meta[$exonGeneIdInAttribute]
        );
    }
    
    echo json_encode($o);
}

elseif($_GET['action'] == 'get_samples') {
    
    $samples = array();
    foreach(glob($dataDir . '/*.bam') as $k => $sample) {
        $samples[] = array('sample_id' => basename($sample), 'filename'=>basename($sample));
    }
    echo json_encode($samples);

}
elseif($_GET['action'] == 'search') {
	$locs = preg_split('/,| |\n/',$_GET['locs']);
	$data = array();
	$regions = array();
	foreach($locs as $loc) {
//	   print $loc;
		if(preg_match('/(\S+):(\d+)\.\.(\d+)/',$loc,$pos)) {
			$d['chr_name'] = $pos[1];
			$d['start'] = (int)$pos[2];
			$d['stop'] = (int)$pos[3];
			$d['genename'] = $d['chr_name'] . ':' . $d['start'] . '-' . $d['stop'];
			$d['location_id'] = $d['chr_name'] . ':' . $d['start'] . '-' . $d['stop'];
			$regions[$d['genename']] = $d;
		} else {
        
            $sql = "select * from gff where feature='$genefeatureName' and attributes like '%$loc%'";
            // "(";
            // foreach($geneIdInAttributes as $att){
                // $sql .= " attributes like '$att%$loc%;' or";
            // }
            // $sql .= " 1!=1 )";
            #echo $sql;
            $results = $db->query($sql);
            
                while ($line = $results->fetchArray(SQLITE3_ASSOC)) {
                #foreach($out as $line) {
                
                $meta = parse_attributes($line['attributes']);
                //print isset($meta['ID']);
                #print_r($line);
                if(!array_key_exists('ID',$meta)) continue;
                
                $d['chr_name'] = $line['seqid'];
                $d['start'] = (int)$line['start'];
                $d['stop'] = (int)$line['end'];
                $d['genename'] = $meta['ID'];
                $d['location_id'] = $d['chr_name'] . ':' . $d['start'] . '-' . $d['stop'];
                $regions[$d['genename']] = $d;
            }
        }
    }
    #print_r($regions);
	if(count($regions) ==0) {
		exit;
	}

    foreach($regions as $k => $region) {
        
        foreach(glob($dataDir . '*.bam') as $sample) {    
            $cmd = $samtools . ' view ' . $sample . ' ' . $region['chr_name'] . ':' 
            . $region['start'] . '-' . $region['stop'] . ' | wc -l';
            // echo $cmd . '<br>';
            $out = array();
            exec($cmd,$out);
            //print_r($out);
            $regions[$k]['cnts'][basename($sample)] = (int)$out[0];
            
        }        
    }
    echo json_encode($regions);

}
elseif($_GET['action'] == 'coverage') {

$start = $_GET['start'];
$stop = $_GET['stop'];
$pixel = $_GET['pixel_size'];

    $chr_name = $_GET['chr_name'];
    $cmd = $samtools . ' view -u ' . $dataDir . $_GET['sample_id'] . ' ' . $chr_name . ':' 
    . $start . '-' . $stop . ' | ' . $samtools . ' pileup - | cut -f 1,2,4';
    
    exec($cmd,$out);
    #print_r($out);
    $summary = array();
    // $summary['index'] = array($start,$stop);
    $summary['data'] = array();
    $current = $start/$pixel;    
    foreach($out as $k => $r) {
    	$d = preg_split("/\t/",$r);
        // print_r($d);
        if(round($d[1]/$pixel) != round($current/$pixel))
            $current = $d[1];
        // print $current . "\n";
        if(array_key_exists($current,$summary['data']))
            $summary['data'][$current] += (int)$d[2]/ $pixel;
        else
            $summary['data'][$current] = (int)$d[2] / $pixel;
    }

    echo json_encode($summary);
}
?>
